/*{
 code:1,
 mess:"", //系统报错的信息 code =0

 }
 {
 code:1,
 mess:"", //系统报错的信息 code =0
 data:{
 业务
 }
 }
 */
(function(global, $) {
    function rest(type, url, data, callback) {
        if (typeof data === "function") {
            callback = data;
            data = {};
        }

        var der = $.Deferred();
        $.ajax({
            type: type,
            url: url,
            data: data,
            dataType:"json",
            // contentType: "application/json;charset=UTF-8",
            success: function(rs) {
                if(rs.mess  === undefined)  rs.mess = null;
                if(rs.code === -1){

                    window.location.href="/admin/login_page.html"
                    // der.resolveWith(this, [rs.mess]);
                }else if (rs.code === 1) {
                    if (typeof callback === 'function') {
                        callback.call(this, rs.mess, rs.data);
                    }
                    der.resolveWith(this, [rs.mess, rs.data]);
                } else {

                    der.rejectWith(this, [rs.mess]);
                }
            },
            error: function() {

                der.rejectWith(this);
            }
        });

        return der.promise();
    }

    $.extend({
        restGet: function() {
            return rest.apply(this, ['GET'].concat(Array.prototype.slice.call(arguments, 0)));
        },
        restPost: function() {
            return rest.apply(this, ['POST'].concat(Array.prototype.slice.call(arguments, 0)));
        }
    });


    //全局 弹出层提示报错 依赖layer 弹出层
    function BaseMessDialog(alert,mess ,time , endcallback) {
        layer.open({
            title: false,
            type: 1,
            closeBtn: 0, //不显示关闭按钮
            shift: 1,
            shadeClose: false, //开启遮罩关闭
            content: '<div class="alert clearmarg '+ alert +'">'+mess +'</div>',
            offset: '100px',
            time: time || 0,
            area: 'auto',
            maxWidth:"auto",
            end :endcallback
        });
}

    $.extend({

        rootErrorDialog:function ( mess,time,endcallback) {
            var rootError= mess || "网络延迟,请刷新";
            return BaseMessDialog("alert-danger",rootError,time,endcallback)
        },
        rootSuccessDialog:function ( mess,time,endcallback) {
            var rootSuccess= mess || "成功了";
            return BaseMessDialog("alert-success",rootSuccess,time,endcallback)
        },
        rootOpenDialog:function (opt) {

            var opt = $.extend({
                title: false,
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                closeBtn: 1, //不显示关闭按钮
                shift: 0,
                offset: '180px',
                shadeClose: false, //开启遮罩关闭
                content: '...',
                area: '460px'
            },opt);
            return layer.open(opt);
        },

        getTime: function (){
        var currDate = new Date();
        var d = new Date();
        var YMDHMS = d.getFullYear() + "-" +(d.getMonth()+1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
        return YMDHMS
        },
        printUrl:'http://114.55.107.209:8082/',
        getUrlLocation:function () {
            var hrefhash = window.location.hash;
            var hrefhashArr=hrefhash.split("/");

            return hrefhashArr[hrefhashArr.length-1];
        },
        funcUrl: function (name, value, type) {
            var loca = window.location;
            var baseUrl = type == undefined ? loca.origin + loca.pathname + "?" : "";
            var query = loca.search.substr(1);
            // 如果没有传参,就返回 search 值 不包含问号
            if (name == undefined) {
                return query
            }
            // 如果没有传值,就返回要查询的参数的值
            if (value == undefined) {
                var val = query.match(new RegExp("(^|&)" + name + "=([^&]*)(&|$)"));
                return val != null ? decodeURI(val[2]) : null;
            }
            ;
            var url;
            if (query == "") {
                // 如果没有 search 值,则返回追加了参数的 url
                url = baseUrl + name + "=" + value;
            } else {
                // 如果没有 search 值,则在其中修改对应的值,并且去重,最后返回 url
                var obj = {};
                var arr = query.split("&");
                for (var i = 0; i < arr.length; i++) {
                    arr[i] = arr[i].split("=");
                    obj[arr[i][0]] = arr[i][1];
                }
                ;
                obj[name] = value;
                url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
            }
            ;
            return url;
        },

        initWebuploader:function (opt) {
            var _opt = {
                server: '/file/upload',
            }

            var playero = null
            var playeroindex = 0

            $.extend(_opt,opt)

            var roomVideo = WebUploader.create({

                idPrefix:'BINLI_TEMP_',

                // 选完文件后，是否自动上传。
                auto: true,

                // swf文件路径
                swf: '/res/lib/webuploader/Uploader.swf',

                // 文件接收服务端。
                server: _opt.server,
                // fileNumLimit: 2,
                duplicate:true,
                chunked: true,
                chunkSize: 2 * 1024 * 1024,
                threads: 1,
                pick: {
                    id: _opt.updom.find(".upbtn"),
                    label: _opt.label
                },
                accept: _opt.accept
            });


            roomVideo.on( 'fileQueued', function( file ) {
                console.log('fileQueued',file)


                $.rootOpenDialog({
                    title:file.name+'上传',
                    closeBtn:false,
                    content:'<div style="padding: 0 10px">' +
                            '<div class="progress" style="margin-top: 15px">' +
                            '  <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0">' +
                                '<span class="degrees">0</span>' +
                            '  </div>' +
                            '</div>' +
                    '</div>',
                    success:function (layero, index) {

                        playero = layero
                        playeroindex = index

                    }
                })


            })

            roomVideo.on( 'uploadSuccess', function( file ,response) {
                console.log('uploadSuccess',file,response)
                layer.close(playeroindex)
                if(response.code == 1){
                    _opt.success && opt.success({
                        data:response.data
                    },opt.updom)
                }else {
                    // alert(data.mess)
                    $.rootErrorDialog(data.mess,1000)
                }

            });
            roomVideo.on( 'uploadError', function( file ) {
                console.log('uploadError')
                layer.close(playeroindex)
                $.rootErrorDialog("上传失败",1000)

            });

            roomVideo.on( 'uploadProgress', function( file, percentage ) {
                    console.log(percentage,Math.floor(percentage*100))
                    $(playero).find(".progress .progress-bar").css({width:Math.floor(percentage*100)+"%"}).find(".degrees").text(Math.floor(percentage*100)+"%")


            });
        },
        createEditor:function (opt) {
            var E = window.wangEditor
            var editor = new E(opt.id)

            var playero = null
            var playeroindex = 0

            editor.customConfig.menus = [
                'head',  // 标题
                'bold',  // 粗体
                'fontSize',  // 字号
                'fontName',  // 字体
                'italic',  // 斜体
                'underline',  // 下划线
                // 'strikeThrough',  // 删除线
                'foreColor',  // 文字颜色
                'backColor',  // 背景颜色
                'code',
                'image',
                'video'
            ]
            editor.customConfig.uploadImgServer = '/file/upload'
            editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024
            editor.customConfig.uploadImgHooks = {
                before: function (xhr, editor, files) {
                    // 图片上传之前触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件

                    // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
                    // return {
                    //     prevent: true,
                    //     msg: '放弃上传'
                    // }

                    console.log(xhr, editor, files)
                    $.rootOpenDialog({
                        title:'上传中。。。',
                        closeBtn:false,
                        content:'<div style="padding:10px">正在上传图片请等待。。。</div>',
                        success:function (layero, index) {

                            playero = layero
                            playeroindex = index

                        }
                    })
                },
                success: function (xhr, editor, result) {
                    console.log(xhr, editor, result)
                    layer.close(playeroindex)
                    $.rootSuccessDialog("上传成功",1000)
                    // 图片上传并返回结果，图片插入成功之后触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                fail: function (xhr, editor, result) {
                    console.log(xhr, editor, result)
                    // 图片上传并返回结果，但图片插入错误时触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果

                    $.rootErrorDialog("上传失败",1000)
                    layer.close(playeroindex)
                },
                error: function (xhr, editor) {
                    console.log(xhr, editor)
                    // 图片上传出错时触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                    layer.close(playeroindex)
                    $.rootErrorDialog("上传失败",1000)
                },
                timeout: function (xhr, editor) {
                    // 图片上传超时时触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },

                // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
                customInsert: function (insertImg, result, editor) {
                    console.log(insertImg, result, editor)
                    // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                    // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

                    // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                    var url = result.data
                    insertImg(url)

                    // result 必须是一个 JSON 格式字符串！！！否则报错
                }
            }

            editor.create()

            return editor
        }
    })

}) (window, jQuery);

Date.prototype.format = function(format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

//分页初始化
function PageCreate(param) {

    this.param = param
}

PageCreate.prototype.init = function (body) {
    var self = this;
    var param = self.param;

    var pageLayer = layer.load(0);
    $.restPost(param.url, body).done(function (msg, data) {
        layer.close(pageLayer)

        param.success && param.success(param.container,data,body);

        //显示分页
        laypage({
            cont: param.pagination, //容器。
            pages: data.pages, //通过后台拿到的总页数
            curr: body.pageNum || 1, //当前页
            skip: true, //是否开启跳页
            skin: 'molv', //皮肤,
            jump: function (obj, first) { //触发分页后的回调
                body.pageNum = obj.curr;
                if (!first) {
                    self.init(body);
                }
            }
        });
    }).fail(function(mess){
        $.rootErrorDialog(mess, 2000)
    });
};



// laypage.dir = '/res/lib/laypage/skin/laypage.css ';

